<template>
  <view class="bg">
    <view class="cell common">
      <u-skeleton
          rows="2"
          :loading="loadingStatus">
        <u-cell-group :border="false">
          <!--图书信息-->
          <u-cell
              :title="dataForm.recordInfo.bookInfo.name"
              :label="dataForm.recordInfo.bookInfo.author"
          >
            <!--封面-->
            <view
                slot="value">
              <u-image
                  :src="dataForm.recordInfo.bookInfo.cover"
                  mode="heightFix"
                  width="7vw"
                  height="10.28vw"
              ></u-image>
            </view>
          </u-cell>
          <u-cell
              title="借阅用户"
              label="点击查看用户联系方式"
              :is-link="true"
              :value="dataForm.recordInfo.userInfo.name"
              @click="userActionStatus=true"
          >
          </u-cell>
          <u-cell
              title="借阅日期"
              label="开始借阅的日期"
              :value="getDate(dataForm.recordInfo.createDate)"
          ></u-cell>
          <u-cell
              title="借阅时长"
              label="点击修改借阅时长"
              :value="`${dataForm.recordInfo.borrowTime}天`"
              :is-link="true"
              @click="timePickerStatus=true"
          ></u-cell>
          <u-cell
              title="到期日期"
              label="可修改借阅时长来调整"
              :value="getDate(dataForm.recordInfo.borrowTime*86400000+dataForm.recordInfo.createDate)"
          ></u-cell>
          <u-cell
              label="点击修改借阅状态"
              :is-link="true"
              :value="getStatus"
              @click="statsPickerStatus=true"
              title="借阅状态">
          </u-cell>
          <u-cell>
            <view slot="icon"><u-text text="备注"></u-text></view>
            <view slot="title">
              <u-textarea
                  placeholder="点击编辑备注信息"
                  :auto-height="true"
                  v-model="dataForm.recordInfo.description"
                  :custom-style="{
                  width:'100%'
                }"
              ></u-textarea>
            </view>
          </u-cell>
          <u-cell
              title="时间轴">
            <!--时间轴-->
            <view
                slot="label"
                class="line-body">
              <view class="line-item" v-for="(item,index) in dataForm.line" :key="index">
                <!--时间-->
                <view class="left">
                  <u-text
                      :text="item.time"
                      type="info"
                      size="12"
                  ></u-text>
                </view>
                <!--步骤点-->
                <view class="mid" :class="{mid_done:!(item.type==='last'),mid_borrow:item.type==='last'}">
                  <!--点-->
                  <view :class="{dot_done:!(item.type==='last'),dot_borrow:item.type==='last'}"></view>
                  <!--进度条-->
                  <view class="process">
                    <u-line
                        v-if="index>0"
                        color="#707070"
                        direction="col"
                        length="20"
                    ></u-line>
                  </view>
                </view>
                <!--信息-->
                <view :class="{right_done:!(item.type==='last'),right_borrow:item.type==='last'}">
                  <u-text
                      v-if="!(item.type==='last')"
                      :text="item.title"
                      type="info"
                      size="12"
                  ></u-text>
                  <u-text
                      v-else
                      :text="item.title"
                      size="12"
                  ></u-text>
                </view>
              </view>
            </view>
          </u-cell>
        </u-cell-group>
        <!--确定-->
        <view class="btn">
          <u-button
              text="确定"
              type="primary"
              shape="circle"
              :disabled="!btnStatus"
              :loading="!btnStatus"
              loading-text="正在保存"
              plain
              @click="updateInfo"
              :custom-style="{
            width:'50vw'
          }"
          ></u-button>
        </view>
      </u-skeleton>
    </view>
    <!--用户ActionSheet-->
    <u-action-sheet
        :actions="dataForm.userActionSheet"
        :show="userActionStatus"
        cancel-text="取消"
        @select="userActionSelect"
        @close="this.userActionStatus=false"
    ></u-action-sheet>
    <!--修改状态-->
    <u-picker
        :show="statsPickerStatus"
        @close="statsPickerStatus=false"
        :columns="statusPickerList"
        :close-on-click-overlay="true"
        @confirm="statusPicker"
        key-name="label"
        title="修改状态"
    ></u-picker>
    <!--修改时长-->
    <u-picker
        :show="timePickerStatus"
        @close="timePickerStatus=false"
        :columns="timePickerList"
        :close-on-click-overlay="true"
        @confirm="timePicker"
        title="修改时间"
    ></u-picker>
    <u-toast ref="uToast"></u-toast>
  </view>
</template>

<script>
export default {
  data() {
    return {
      dataForm:{
        recordInfo: {},
        line: [],
        userActionSheet:[],
        // record更新信息
        updateItem:{},
        // action新增信息
        updateAction:{},
        updateActionStatus:false
      },
      statusPickerList: [
        [
          {
            label: '借阅中',
            value:'borrow'
          },
          {
            label: '已归还',
            value: 'back'
          }
        ]
      ],
      timePickerList:[
        [1,3,7,14,21,28,35,42,49,56,63,70]
      ],
      loadingStatus: true,
      btnStatus:true,
      timePickerStatus:false,
      userActionStatus:false,
      statsPickerStatus:false
    }
  },
  methods: {
    //获取记录详细信息
    async getRecordInfo(recordId) {
      this.loadingStatus = true
      // 清空本地信息
      this.dataForm = {
        recordInfo: {},
        line: [],
        userActionSheet:[],
        // record更新信息
        updateItem:{},
        // action新增信息
        updateAction:{},
        updateActionStatus:false
      }
      try {
        let db = uniCloud.database()
        let dbCmd = db.command
        let $ = dbCmd.aggregate
        let recordRes = (await db.collection('record')
            .aggregate()
            .match({
              _id: recordId
            })
            .lookup({
              from:'record_action',
              let:{
                rId:'$_id',
              },
              pipeline:$.pipeline()
                  .match(dbCmd.expr($.eq(['$recordId','$$rId'])))
                  .lookup({
                    from:'user',
                    let:{
                      uId:'$userId'
                    },
                    pipeline:$.pipeline()
                        .match(dbCmd.expr($.eq(['$_id','$$uId'])))
                        .project({
                          name:1
                        })
                        .done(),
                    as:'userInfo',
                  })
                  .unwind('$userInfo')
                  .project({
                    date:1,
                    status:1,
                    userInfo:1
                  })
                  .done(),
              as:'actionList'
            })
            .lookup({
              from:'book',
              let:{
                bId:'$bookId'
              },
              pipeline:$.pipeline()
                  .match(dbCmd.expr($.eq(['$_id','$$bId'])))
                  .project({
                    cover:1,
                    name:1,
                    author:1
                  })
                  .done(),
              as:'bookInfo'
            })
            .unwind('$bookInfo')
            .lookup({
              from:'user',
              let:{
                uId:'$userId'
              },
              pipeline:$.pipeline()
                  .match(dbCmd.expr($.eq(['$_id','$$uId'])))
                  .project({
                    name:1,
                    tel:1,
                    email:1
                  })
                  .done(),
              as:'userInfo',
            })
            .unwind('$userInfo')
            .project({
              actionList:1,
              bookInfo:1,
              borrowTime:1,
              createDate:1,
              status:1,
              description:1,
              userInfo:1
            })
            .end()).result.data
        if (recordRes.length > 0) {
          this.dataForm.recordInfo = recordRes[0]
          this.createUserAction(recordRes[0].userInfo)
          this.createLine(recordRes[0].actionList)
          this.dataForm.updateItem={
            borrowTime: recordRes[0].borrowTime,
            status:recordRes[0].status
          }
        }
      } catch (e) {
        console.log(e)
        this.$refs.uToast.show({
          message: String(e) || '获取记录信息失败',
          type: 'error'
        })
      } finally {
        uni.stopPullDownRefresh()
        this.loadingStatus = false
      }
    },
    createLine(list){
      list.forEach((value,index,array)=>{
        let item = {
          title:'',
          time:this.getDate(value.date),
          type:index === array.length-1 ? 'last':''
        }
        let name = value.userInfo.name
        switch (value.status) {
          case 'borrow':item.title=`${name}开始借阅`;break
          case 'backing':item.title=`${name}申请归还`;break
          case 'back':item.title=`${name}确认归还`;break
          default:break
        }
        this.dataForm.line.push(item)
      })
    },
    // 生成用户联系信息选项
    createUserAction(userInfo){
      this.dataForm.userActionSheet.push({
        name: '电话',
        subname: userInfo.tel,
        param:'tel'
      })
      this.dataForm.userActionSheet.push({
        name:'邮箱',
        subname: userInfo.email,
        param:'email'
      })
    },
    // 获取UTC格式时间
    getDate(timestamp) {
      if (timestamp === null || timestamp === '')
        return ''
      let date = new Date(timestamp)
      let Y = date.getFullYear() + '-'
      let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
      let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate())
      return String(Y + M + D)
    },
    // 用户联系信息点击
    userActionSelect(item){
      let _this = this
      switch (item.param) {
        case 'tel':{
          uni.makePhoneCall({
            phoneNumber: item.subname,
            fail(){
              _this.$refs.uToast.show({
                message: '拨打电话失败',
                type: 'error'
              })
            }
          })
        }break;
        case 'email':{
          uni.setClipboardData({
            data: item.subname,
            success(){
              _this.$refs.uToast.show({
                message: '成功复制邮箱地址至剪贴板',
                type:'success'
              })
            },
            fail(){
              _this.$refs.uToast.show({
                message: '复制邮箱地址至剪贴板失败',
                type:'error'
              })
            }
          })
        }break;
        default:break;
      }
    },
    // 状态选择器
    statusPicker(value){
      let status = value.value[0].value
      // 如果选择了借阅中
      if(status==='borrow'){
        // 检查是否逾期
        if (this.dataForm.recordInfo.createDate+this.dataForm.recordInfo.borrowTime*86400000 < Date.now()){
          // 逾期节约时长自动加7
          this.dataForm.updateItem.borrowTime = this.dataForm.recordInfo.borrowTime+7
        }
      }
      // 检查是否修改了借阅状态
      if(status!==this.dataForm.recordInfo.status){
        this.dataForm.updateActionStatus = true
        let userInfo = uni.getStorageSync('userInfo')
        this.dataForm.updateAction={
          userId:userInfo._id,
          recordId:this.dataForm.recordInfo._id,
          status:status,
        }
      }
      this.dataForm.updateItem.status = status
      this.statsPickerStatus = false
    },
    // 时间选择器
    timePicker(value){
      this.dataForm.updateItem.borrowTime = value.value[0]
      this.dataForm.recordInfo.borrowTime = value.value[0]
      this.timePickerStatus = false
    },
    // 更新信息
    async updateInfo(){
      this.btnStatus=false
      try {
        let db = uniCloud.database()
        // 更借阅记录
        await db.collection('record')
            .doc(this.dataForm.recordInfo._id)
            .update({
              ...this.dataForm.updateItem,
              description:this.dataForm.recordInfo.description
            })
        // 更新借阅记录操作
        if(this.dataForm.updateActionStatus){
          await db.collection('record_action')
              .add(this.dataForm.updateAction)
        }
        // 更新书的状态
        await db.collection('book')
            .doc(this.dataForm.recordInfo.bookInfo._id)
            .update({
              status:(this.dataForm.updateAction.status === 'back')
            })
        this.$refs.uToast.show({
          message: '保存成功',
          type:'success'
        })
        await this.getRecordInfo(this.dataForm.recordInfo._id)
      }catch (e) {
        console.log(e)
        this.$refs.uToast.show({
          message:String(e)||'保存失败',
          type: 'error'
        })
      }finally {
        this.btnStatus=true
      }
    }
  },
  computed: {
    getStatus() {
      switch (this.dataForm.updateItem.status) {
        case "borrow": {
          if (this.dataForm.recordInfo.createDate + this.dataForm.recordInfo.borrowTime * 86400000 < Date.now()) {
            return "已逾期"
          } else {
            return "借阅中"
          }
        }
        case "backing":
          return "待确认"
        case "back":
          return "已归还"
      }
    }
  },
  onLoad(query) {
    if (query.recordId) {
      this.dataForm.recordInfo._id = query.recordId
      this.getRecordInfo(query.recordId)
    }
  },
  onPullDownRefresh() {
    this.getRecordInfo(this.dataForm.recordInfo._id)
  }
}
</script>

<style lang="scss">
.bg {
  padding: 15px 0;
  min-height: calc(100vh - 15px);
}

.cell {

}

.btn{
  display: flex;
  justify-content: center;
  width: 100%;
  margin-top: 20px;
}

.line-body {
  display: flex;
  flex-direction: column-reverse;
  margin-top: 10px;

  .line-item {
    display: flex;

    .left {

    }

    .mid {
      display: flex;
      flex-direction: column;
      align-items: center;

      .dot_done {
        align-self: center;
        margin-top: 3px;
        border-radius: 100%;
        height: 10px;
        width: 10px;
        background: #707070;
      }

      .dot_borrow {
        margin-top: 2px;
        align-self: center;
        border-radius: 100%;
        height: 14px;
        width: 14px;
        background: #3c9cff;
      }

      .process {
        margin-top: 4px;
        align-self: center;
        display: flex;
        justify-content: center;
      }
    }

    .mid_done {
      margin-left: 14px;
    }

    .mid_borrow {
      margin-left: 12px;
    }

    .right_done {
      margin-left: 12px;
    }

    .right_borrow {
      margin-left: 10px;
    }
  }
}

</style>